﻿using System;
using System.Xml;
using System.Globalization;
using InfoJetSoft.Service.Entity;

namespace InfoJetSoft.Service.Util {
	
	public class DateFormater {
		
		public static string format(Form form, XmlNode node, string value_Renamed, TypeFormat format, bool isDeformat) {
			if (value_Renamed.Trim().Length <= 0) {
				return "";
			}
			string dateFormat = format.DateFormat;
			if (dateFormat == null) {
				dateFormat = "yyyy-M-d";
			}
			
			CultureInfo locale = LocaleUtil.getLocale( format );
			SimpleDateFormat sdf = new SimpleDateFormat(dateFormat, locale );
			System.DateTime date;
			try {
				date = sdf.parse( value_Renamed );
			}
			catch (System.FormatException e1) {
				DdddDateTime ddddDate = DdddDateTime.ddddParse( value_Renamed, dateFormat, locale );
				if( !ddddDate.Valid ){
					try {
						SimpleDateFormat tryYyyyMdormat = new SimpleDateFormat("yyyy-M-d");
						date = tryYyyyMdormat.parseExact( value_Renamed );
					}
					catch (System.FormatException e2) {
						try {
							SimpleDateFormat tryYyyyMFormat = new SimpleDateFormat("yyyy-M");
							date = tryYyyyMFormat.parseExact( value_Renamed );
						}
						catch (System.FormatException e3) {
							try 
							{
								SimpleDateFormat tryYyyyMMddFormat = new SimpleDateFormat("yyyyMMdd");
								date = tryYyyyMMddFormat.parseExact( value_Renamed );
							}
							catch (System.FormatException e4) 
							{
								return value_Renamed;
							}
						}
					}
				}else{
					date = ddddDate.DateTime;
				}
			}
			SimpleDateFormat storeFormat = new SimpleDateFormat("yyyy-MM-dd");
			string nodeValue = storeFormat.format(date);
			nodeValue = FormatUtil.formatDateTimeZ( nodeValue );

			if( isDeformat )
			{
				FormUtil.updateFormattingNode(form, node, nodeValue);
			}
			return sdf.format(date);
		}

	}

}